package per.jdz.circuitbreaker;

import java.lang.reflect.Method;
import java.util.HashSet;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

import per.jdz.circuitbreaker.proxy.CircuitBreakerProxyFactory;

@Configuration
public class CircuitBreakerBeanPostProcessor implements BeanPostProcessor {

    private ICircuitBreakerController iCircuitBreakerController;

    public CircuitBreakerBeanPostProcessor(ICircuitBreakerController iCircuitBreakerController) {
        this.iCircuitBreakerController = iCircuitBreakerController;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 找到方法标有注解的收集
        final Class aclass = bean.getClass();
        final HashSet<Integer> methodsHashCode = new HashSet<>();
        for (Method method : aclass.getDeclaredMethods()) {
            if (method.isAnnotationPresent(CircuitBreaker.class)) {
                methodsHashCode.add(method.hashCode());
            }
        }
        // 生成代理对象
        if (!methodsHashCode.isEmpty()) {
            try {
                return CircuitBreakerProxyFactory.getProxy(bean, methodsHashCode, iCircuitBreakerController);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return bean;
    }

}